#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import sys, asyncio
from aiohttp import web

sys.path.append('..')

from conf.configs import *
from spider.spider import request_catalog
from spider.orm import Db


def index(request):
    return web.Response(body=b'<h1>Awesome</h1>', headers={'Content-Type': 'text/html;utf-8'})


def catalog(request):
    response = request_catalog('http://www.ppxs.net/73/73248/')

    return web.Response(body=str(response), headers={'Content-Type': 'text/html;utf-8'})




@asyncio.coroutine
def init(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/catalog', catalog)
    app.router.add_route('GET', '/', index)

    if not os.path.exists(configs['db_path']):
        db = Db(configs['db_path'])
        db.initialize(configs['sql_path'])

    srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 9999)
    logging.info('server started at http://127.0.0.1:9999...')
    return srv


loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
